package com.xunk.system.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xunk.common.core.domain.UploadFile;
import com.xunk.common.core.exception.CustomException;
import com.xunk.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ProjectName: xunk
 * @Package: com.xunk.system.service
 * @ClassName: UploadFileService
 * @Author: dongxiaoxin
 * @Description: 上传文件服务
 * @Date: 2021/5/10 17:29
 * @Version: 1.0
 */
@Slf4j
@Service
public class UploadFileService {


    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 域名或本机访问地址
     */
    @Value("${fdfs.domain}")
    public String domain;

    /**
     * 单文件上传
     *
     * @param file 单一文件
     * @return 上传文件口返回的存储链接
     * @throws IOException
     */
    public UploadFile uploadFile(MultipartFile file) throws IOException {

        if (Objects.isNull(file)) {
            throw new CustomException("上传文件为空");
        }
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                getFileExtension(file), null);
        String fullPath = storePath.getFullPath();
        return new UploadFile(file.getOriginalFilename(), domain, fullPath);
    }

    /**
     * 多文件上传
     *
     * @param files 多文件
     * @return
     */
    public List<UploadFile> uploadFiles(MultipartFile[] files) throws IOException {

        if (files == null || files.length == 0) {
            throw new CustomException("上传文件为空");
        }
        if (files.length > 9) {
            throw new CustomException("一次最多上传9个文件");
        }
        List<UploadFile> urls = new ArrayList<>();
        for (MultipartFile file : files) {

            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                    getFileExtension(file), null);
            String fullPath = storePath.getFullPath();
            urls.add(new UploadFile(file.getOriginalFilename(), domain, fullPath));
        }
        return urls;
    }

    private String getFileExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        return StringUtils.isEmpty(extension) ? Objects.requireNonNull(file.getContentType()).substring(file.getContentType().indexOf("/") + 1) : extension;
    }
}
